package com.programmercarl.hash;

import java.util.*;

/**
 * https://leetcode.cn/problems/3sum/description/
 *
 * @author yulongtian
 * @create 2024-12-14 19:15
 */
public class Test05 {
    public static void main(String[] args) {
        int[] arr = new int[]{-1, 0, 1, 2, -1, -4};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        System.out.println(threeSum(arr));
    }

    /**
     * 双指针方法
     *
     * @param nums
     * @return
     */
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    left++;
                    right--;
                } else if (sum > 0) {
                    right--;
                } else if (sum < 0) {
                    left++;
                }
            }
        }
        return res;
    }

    /**
     * 哈希表方法超时
     *
     * @param nums
     * @return
     */
    public static List<List<Integer>> threeSum1(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        HashSet<List<Integer>> index = new HashSet<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            int sum = -nums[i];
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int j = i + 1; j < nums.length; j++) {
                if (map.containsKey(sum - nums[j])) {
                    Integer k = map.get(sum - nums[j]);
                    ArrayList<Integer> temp = new ArrayList<>(3);
                    temp.add(nums[i]);
                    temp.add(nums[j]);
                    temp.add(nums[k]);
                    temp.sort(Comparator.comparingInt(a -> a));
                    if (!index.contains(temp)) {
                        index.add(temp);
                        res.add(temp);
                    }
                } else {
                    map.put(nums[j], j);
                }
            }
        }

        return res;
    }

}
